import React from 'react';
import { inject, observer } from 'mobx-react';
import ExcelLayout from '../excel-layout';
import { WeaReqTop, WeaRightMenu, WeaAlertPage, WeaLocaleProvider, WeaSlideModal, WeaTools } from 'ecCom';
import CardStore from '../../stores/card';
import { listStore } from '../../stores/list'
import TopTabs from './TopTabs';
import { DetailImportDialog } from './DetailImport';
import Reply from '../reply/reply';
import ReplySingle from '../reply/replySingle';
import RightReply from '../reply/rightReply';
import { SingleShareDialog } from '../../pages/batch-share/Single';
import { MapAddressDialog } from '../cube-map'
import CustomDialog from './CustomDialog';
import RightLeftLayout from './RightLeftLayout';
import window from '../../util';
import List from '../list';
import LogList from '../../pages/log-list';
import _ from 'lodash';
import jQuery from 'jquery';
import { CustomPageStore } from '../../stores/custompage';
import { TreeStore } from '../../stores/tree';
import ReplyStore from '../../stores/reply';
import { LogListStore } from '../../stores/list/LogListStore';
import classNames from 'classnames';
import { PreviewCard } from './PreviewCard';
import * as DetailUtil from '../../util/cubeUtil';
import { computed } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;

export interface InnerTabCardProps {
    Card: CardStore;
    Search: listStore;
    hideRightmenu?: boolean;
}

export interface CardProps {
    Card: CardStore;
    Search: listStore;
    Tree: TreeStore;
    reply: ReplyStore;
    customPageStore: CustomPageStore;
    cubeLogList: LogListStore;
}

@observer
export class InnerTabCard extends React.Component<InnerTabCardProps, any> {
    getBottomHeight = () => {
        const toptabsHeight = jQuery('.coms-mode-card').find('.cube-card-toptabs').outerHeight();
        const topHeight = jQuery('.coms-mode-card').find('.wea-new-top-req-wapper').find('.wea-new-top-req').height();
        let h = document.documentElement.clientHeight - topHeight - toptabsHeight;
        return h - 1;
    }

    render() {
        const { Card, hideRightmenu = false } = this.props;
        const { verified, hasRight, iconInfo, cardMarginParams: { padding } } = Card;
        if (verified && !hasRight) {
            return (<WeaAlertPage>
                <div style={{ color: '#000' }}>
                    {getLabel(2012, '对不起，您暂时没有权限！')}
                </div>
            </WeaAlertPage>
            )
        }
        if (verified && hasRight) {
            let arr: any = [];
            if (Card.isInit) {
                if (Card.reply && Card.base.showReply && Card.base.type == '0') {
                    if (Card.base.replyposition == 1) {//底部
                        arr.push(<ExcelLayout Card={Card} />);
                        arr.push(<Reply reply={Card.reply} padding={padding} />);
                    } else if (Card.base.replyposition == 2) {//右
                        let bottomHeight = this.getBottomHeight();
                        let visible = Card.base.defaultcontraction == '1'
                        //回复评论在右侧的时候，页面边距这里处理 ---1
                        arr.push(
                            <RightLeftLayout
                                padding={padding}
                                visible={visible}
                                bottomHeight={bottomHeight - padding.top - padding.bottom}
                                leftCom={<ExcelLayout Card={Card} />}
                                iconClass={"icon-coms-Advice"}
                                titletext={getLabel(128283, '回复评论')}
                                rightCom={<RightReply reply={Card.reply} h={bottomHeight - padding.top - padding.bottom} />}
                            />
                        )
                    } else {
                        arr.push(<ExcelLayout Card={Card} />);
                    }
                } else {
                    arr.push(<ExcelLayout Card={Card} />);
                }
            }
            const childComponent = <React.Fragment>
                <div className="cube-card-layout">
                    {arr}
                </div>
                <DetailImportDialog detailImport={Card.detailImport} iconInfo={iconInfo} ecme={{ boolean: false }} />
                <SingleShareDialog
                    iconInfo={iconInfo}
                    share={Card.share}
                    formId={Card.base.formId}
                    modeId={Card.base.modeId}
                    nonDefaultShared={Card.base.nondefaultshared}
                    defaultShared={Card.base.defaultshared}
                    type="0"
                />
                <MapAddressDialog mapStore={Card.mapStore} iconInfo={iconInfo} />
                <CustomDialog customDialog={Card.customDialog} iconInfo={iconInfo} />
            </React.Fragment>
            if (hideRightmenu) {
                return <div className="cube-card-inline-wrapper">
                    <div className="cube-card-inline-tab">
                        {childComponent}
                    </div>
                </div>
            }
            return (
                <div className="cube-card-inline-wrapper">
                    <div className="cube-card-inline-tab">
                        <WeaRightMenu
                            datas={Card.cardTab.rightMenus.slice()}
                            onClick={Card.cardTab.rightMenuHandle}
                        >
                            {childComponent}
                        </WeaRightMenu>
                    </div>
                </div>
            )
        }
        return (<div></div>)
    }
}

@inject('Card', 'Search', 'Tree', 'reply', 'customPageStore', 'cubeLogList')
@observer
export default class Card extends React.Component<CardProps, any> {

    componentDidMount() {
        window.perfectHeight = () => {
            const toptabsHeight = jQuery('.coms-mode-card').find('.cube-card-toptabs').outerHeight();
            const topHeight = jQuery('.coms-mode-card').find('.wea-new-top-req-wapper').find('.wea-new-top-req').height();
            const bodyHeight = jQuery('.coms-mode-card').find('.wea-new-top-req-wapper').find('.wea-new-top-req-content').prop('scrollHeight');
            return bodyHeight + topHeight + toptabsHeight;
        }
    }

    getBottomHeight = () => {
        const toptabsHeight = jQuery('.coms-mode-card').find('.cube-card-toptabs').outerHeight();
        const topHeight = jQuery('.coms-mode-card').find('.wea-new-top-req-wapper').find('.wea-new-top-req').height();
        let h = document.documentElement.clientHeight - topHeight - toptabsHeight;
        return h - 1;
    }

    getExcelAndReplayCom = () => {
        const { Card } = this.props;
        const { cardMarginParams: { padding } } = Card;
        let arr = new Array();
        if (Card.reply && Card.base.showReply && Card.base.type == '0') {
            if (Card.base.replyposition == 1) {//底部
                arr.push(<ExcelLayout Card={Card} />);
                arr.push(<Reply reply={Card.reply} padding={padding} />);
            } else if (Card.base.replyposition == 2) {//右侧
                let bottomHeight = this.getBottomHeight();
                let visible = Card.base.defaultcontraction == '1'
                //回复评论在右侧的时候，页面边距这里处理 ---1
                arr.push(
                    <RightLeftLayout
                        padding={padding}
                        visible={visible}
                        bottomHeight={bottomHeight - padding.top - padding.bottom}
                        leftCom={<ExcelLayout Card={Card} />}
                        iconClass={"icon-coms-Advice"}
                        titletext={getLabel(128283, '回复评论')}
                        rightCom={<RightReply reply={Card.reply} h={bottomHeight - padding.top - padding.bottom} />}
                    />
                )
            } else {
                arr.push(<ExcelLayout Card={Card} />);
            }
        } else {
            arr.push(<ExcelLayout Card={Card} />);
        }

        return arr;
    }
    doScrollYEvent() {
        DetailUtil.fixedDetailHead();   //明细表头固定
    }

    render() {
        const { Card, Search, cubeLogList } = this.props;
        const { verified, hasRight, iconInfo, windowTitle, sliderParams } = Card;
        if (windowTitle != '') {
            document.title = windowTitle;
        }

        if (verified && !hasRight) {
            return (<WeaAlertPage>
                <div style={{ color: '#000' }}>
                    {getLabel(2012, '对不起，您暂时没有权限！')}
                </div>
            </WeaAlertPage>
            )
        }
        if (verified && hasRight) {
            if (Card.params.type == '4') {
                return (
                    Card.isInit ?
                        <ExcelLayout Card={Card} /> :
                        <div></div>
                )
            }

            if (Card.params.isPreview && ((Card.params.isPreview | 0) == 1)) {
                return <PreviewCard Card={Card} />
            }
            if (Card.params.hidetop && ((Card.params.hidetop | 0) === 1)) {
                return <InnerTabCard Card={Card} Search={Search} />
            }

            return (
                <TopTabs
                    modeName={getLabel(1361, "基本信息")}
                    onTabClick={Card.cardTab.changeTopActiveKey}
                    topTabs={Card.cardTab.topTabs && Card.cardTab.topTabs.slice()}
                    activeKey={Card.cardTab.topActiveKey}
                    activeDropKey={Card.cardTab.topDropActiveKey}
                    isCube={Card.cardTab.isCube}
                    url={Card.cardTab.hrefUrl}
                    Search={this.props.Search}
                    Tree={this.props.Tree}
                    Reply={this.props.reply}
                    Custompage={this.props.customPageStore}
                >
                    <WeaRightMenu
                        datas={Card.cardTab.rightMenusToShow.slice()}
                        onClick={Card.cardTab.rightMenuHandle}
                        collectParams={{
                            "favname": getLabel(1361, "基本信息"),
                            "link": '/' + window.location.toString().split('/').slice(3).join('/'),
                            "favouritetype": 5,
                            "importantlevel": 1
                        }}
                    >
                        <div
                            className={classNames({ 'cube-card-top-wrapper-no-tabs': !Card.cardTab.tabDatas.slice().length })}>
                            <WeaReqTop
                                loading={Card.isShowLoading}
                                title={<div title={Card.cardTab.title}>{Card.cardTab.title}</div>}
                                icon={<i className={iconInfo.icon} style={{ color: iconInfo.iconColor }} />}
                                iconBgcolor={iconInfo.iconBg}
                                tabDatas={Card.cardTab.tabDatas.slice()}
                                onChange={Card.cardTab.changeInnerTabSelectedKey}
                                selectedKey={Card.cardTab.innerTabSelectedKey}
                                onDropMenuClick={Card.cardTab.rightMenuHandle}
                                {...this.getRightMenusProps}
                            >
                                {Card.cardTab.innerTabSelectedKey == '1000' && Card.isInit &&
                                    <div className="cube-card-form-content" onScroll={this.doScrollYEvent.bind(this)}>
                                        {this.getExcelAndReplayCom()}
                                    </div>

                                }
                                {
                                    Card.isSearchShow && Search.isInit &&
                                    <div className="cube-card-list-wrapper">
                                        <List Search={Search} hideRightmenu={true} />
                                    </div>
                                }
                                {
                                    Card.isCardShow && Card.card.isInit &&
                                    <InnerTabCard Card={Card.card} Search={Search} hideRightmenu={true} />
                                }
                                {
                                    Card.isLogListShow &&
                                    <div className="cube-card-list-wrapper">
                                        <LogList cubeLogList={cubeLogList} />
                                    </div>
                                }
                                {
                                    Card.isShowReply && Card.reply && (Card.base.type == '0' || Card.base.type == '2') &&
                                    <div style={{ paddingTop: 25 }}>
                                        {Card.base.showReply ? <ReplySingle reply={Card.reply} />
                                            : Card.base.showReply === false ? <div
                                                className="cube-no-open-reply">{getLabel("391240", "请联系管理员后台开启回复评论功能！")}</div>
                                                : null
                                            // <ReplySingle reply={Card.reply}/> 
                                        }
                                    </div>
                                }
                                <div className="cube-card-iframe" style={{ display: 'none' }}>
                                    <iframe onLoad={() => {
                                        Card.changeLoadingState()
                                    }} id="tabcontentframe" name="tabcontentframe" width="100%" height="100%"
                                        frameBorder={0}
                                        scrolling="no" style={{ display: 'none' }} />
                                </div>
                                <DetailImportDialog detailImport={Card.detailImport} iconInfo={iconInfo} ecme={{ boolean: false }} />
                                <SingleShareDialog
                                    iconInfo={iconInfo}
                                    share={Card.share}
                                    formId={Card.base.formId}
                                    modeId={Card.base.modeId}
                                    nonDefaultShared={Card.base.nondefaultshared}
                                    defaultShared={Card.base.defaultshared}
                                    type="0"
                                />
                                <MapAddressDialog mapStore={Card.mapStore} iconInfo={iconInfo} />
                                <CustomDialog customDialog={Card.customDialog} iconInfo={iconInfo} />
                                <div onClick={(e) => e.stopPropagation()} className={"Cube-card-WeaSlideModal"}>
                                    <WeaSlideModal
                                        visible={Card.slideModalVisible}
                                        top={this.slideStyle.newtop + "px"}
                                        width={((this.slideStyle.width) * parseFloat(sliderParams.sliderPercentage) / 100) + "px"}
                                        height={(this.slideStyle.height) + "px"}
                                        direction={'right'}
                                        measure={''}
                                        style={{ overflowY: "hidden" }}
                                        content={(
                                            <iframe src={sliderParams.slideModalUrl}
                                                name={"iframe_" + new Date().getTime()} style={{
                                                    border: "0",
                                                    height: "100%",
                                                    width: "100%"
                                                }}></iframe>
                                        )}
                                        onClose={this.slideModalClose}
                                    />
                                </div>
                            </WeaReqTop>
                        </div>
                    </WeaRightMenu>
                </TopTabs>
            )
        }
        return (<div></div>)
    }

    slideModalClose = () => {
        const { Card } = this.props;
        Card.showSlideModal(false, "", "")
    }

    @computed
    get slideStyle() {
        const themelayoutType = (WeaTools.ls.getJSONObj('theme-themeInfo') && WeaTools.ls.getJSONObj('theme-themeInfo').themeLayoutType) || "1"; //门户布局
        let newtop = 0;
        if (themelayoutType == '1') { //默认布局
            newtop = jQuery(".e9theme-layout-main").offset() ? (jQuery(".e9theme-layout-main").offset().top ? jQuery(".e9theme-layout-main").offset().top + 10 : 0) : 0;
        } else {
            newtop = jQuery(`.e9theme-layout${themelayoutType}-main`).offset() ? (jQuery(`.e9theme-layout${themelayoutType}-main`).offset().top ? jQuery(`.e9theme-layout${themelayoutType}-main`).offset().top + 10 : 0) : 0;
        }
        if (newtop == 0) {
            newtop = jQuery(".e8theme-layout-main").offset() ? (jQuery(".e8theme-layout-main").offset().top ? jQuery(".e8theme-layout-main").offset().top + 10 : 0) : 0;
        }
        /***计算left */
        let left = jQuery(".e9theme-layout-main").offset() ? (jQuery(".e9theme-layout-main").offset().left ? jQuery(".e9theme-layout-main").offset().left + 10 : 0) : 0;
        if (left == 0) {
            left = jQuery(".e8theme-layout-main").offset() ? (jQuery(".e8theme-layout-main").offset().left ? jQuery(".e8theme-layout-main").offset().left + 10 : 0) : 0;
            if (left == 0) {
                left = jQuery(".cube-tree-list").css('width');
                if (left == undefined) {
                    left = 0;
                } else {
                    left = left.replace('px', '') - 14;
                }
            } else {
                let treeleft = jQuery(".cube-tree-list").css('width');
                if (treeleft == undefined) {
                    treeleft = 0;
                } else {
                    left = left + parseFloat(treeleft.replace('px', '')) - 10;
                }
            }
        } else {
            let treeleft = jQuery(".cube-tree-list").css('width');
            if (treeleft == undefined) {
                treeleft = 0;
            } else {
                left = left + parseFloat(treeleft.replace('px', '')) - 10;
            }
        }

        let scrollheigth = document.documentElement.clientHeight - newtop;
        let scrollwidth = document.documentElement.clientWidth - left;

        return { height: scrollheigth, width: scrollwidth, newtop: newtop }
    }

    @computed
    get getRightMenusProps() {
        const { Card } = this.props;
        const rightMenusProps: any = {};
        if (Card.cardTab.quickButtons.slice().length > 0) {
            _.set(rightMenusProps, 'buttons', Card.cardTab.quickButtons.slice());
        }
        if (Card.cardTab.rightMenusToShow.slice().length > 0) {
            _.set(rightMenusProps, 'dropMenuDatas', Card.cardTab.rightMenusToShow.slice());
            _.set(rightMenusProps, 'showDropIcon', true);
        } else {
            _.set(rightMenusProps, 'showDropIcon', false);
        }
        return rightMenusProps;
    }

}

